package com.chhuang.uresource.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.chhuang.core.service.impl.BaseServiceImpl;
import com.chhuang.core.bean.QueryBean;
import com.chhuang.utils.Assert;
import com.chhuang.uresource.bean.ChLogQueryBean;
import com.chhuang.uresource.po.ChLog;
import com.chhuang.uresource.po.ChLogExample;
import com.chhuang.uresource.mapper.ChLogMapper;
import com.chhuang.uresource.service.IChLogService;

/**
* ChLog ServiceImpl
* @author ChHuang
* @date Wed May 09 13:52:26 CST 2018
*/
@Service
public class ChLogServiceImpl extends BaseServiceImpl<ChLogMapper, ChLog> implements IChLogService {
	@Autowired
	private ChLogMapper chLogMapper;

	@Override
	public QueryBean<ChLog> seniorQuery(QueryBean<ChLog> queryBean) throws Exception {
		ChLogQueryBean poQueryBean = (ChLogQueryBean)queryBean;
		ChLogExample example = new ChLogExample();
		
		if(poQueryBean.isAnd()){//全部是与条件
			ChLogExample.Criteria criteria = example.createCriteria();
			if(Assert.isValidString(poQueryBean.getLogId())){
				criteria.andLogIdEqualTo(poQueryBean.getLogId());
			}
			if(Assert.isValidString(poQueryBean.getUserId())){
				criteria.andUserIdLike("%"+poQueryBean.getUserId()+"%");
			}
			if(Assert.isValidString(poQueryBean.getUsername())){
				criteria.andUsernameLike("%"+poQueryBean.getUsername()+"%");
			}
			if(Assert.isValidString(poQueryBean.getLog())){
				criteria.andLogLike("%"+poQueryBean.getLog()+"%");
			}
			if(poQueryBean.getCreateTime() != null){
				criteria.andCreateTimeEqualTo(poQueryBean.getCreateTime());
			}
		}else{//全部是或条件
			if(Assert.isValidString(poQueryBean.getLogId())){
				example.or().andLogIdEqualTo(poQueryBean.getLogId());
			}
			if(Assert.isValidString(poQueryBean.getUserId())){
				example.or().andUserIdLike("%"+poQueryBean.getUserId()+"%");
			}
			if(Assert.isValidString(poQueryBean.getUsername())){
				example.or().andUsernameLike("%"+poQueryBean.getUsername()+"%");
			}
			if(Assert.isValidString(poQueryBean.getLog())){
				example.or().andLogLike("%"+poQueryBean.getLog()+"%");
			}
			if(poQueryBean.getCreateTime() != null){
				example.or().andCreateTimeEqualTo(poQueryBean.getCreateTime());
			}
		}
		
		poQueryBean.setItemCount(chLogMapper.countByExample(example));//总记录数
		if(poQueryBean.getItemCount()>0){//计算总页数
			poQueryBean.setPageCount(poQueryBean.getItemCount()/poQueryBean.getPageSize()+
					(int)(poQueryBean.getItemCount()%poQueryBean.getPageSize()>0?1:0));
			if(poQueryBean.getPageCount()>=poQueryBean.getPageNum()){
				if(Assert.isValidString(poQueryBean.getOrderBy())){//排序
					example.setOrderByClause(poQueryBean.getOrderBy()+" "+poQueryBean.getOrder());
				}
				//分页
				example.setOffset((poQueryBean.getPageNum()-1)*poQueryBean.getPageSize());
				example.setLimit(poQueryBean.getPageSize());
				poQueryBean.setResult(chLogMapper.selectByExample(example));
			}
		}
		
		return poQueryBean;
	}
}